package com.localsocial.phonescreen;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.localsocial.Device;
import com.localsocial.LocalSocial;
import com.localsocial.LocalSocialFactory;
import com.localsocial.Platform;
import com.localsocial.config.SimpleAppConfiguration;
import com.localsocial.model.Tag;
import com.localsocial.oauth.AccessToken;
import com.localsocial.oauth.OAuthConsumer;
import com.localsocial.oauth.RequestToken;
import com.localsocial.oauth.Verifier;
import com.localsocial.proximity.PeriodicScan;
import com.localsocial.proximity.observers.NeighbourhoodObserver;
import com.localsocial.remote.RemoteFactory;
import com.localsocial.remote.exception.ParseException;
import com.localsocial.remote.exception.UnauthorizedException;

import oauth.signpost.OAuth;
//import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

public class temp extends Activity {
	
	private final String TAG = getClass().getName();
	private PeriodicScan m_scan;
	private SharedPreferences prefs;
	
	//private final int BT_ON = 1;
	private String screen_bt = null;
	
	public static LocalSocial m_localsocial;
	public static String m_local_mac;
	public static AccessToken m_access_token;
	private OAuthConsumer m_consumer;
	private String m_address = null;
	private RemoteFactory m_remote;
	
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;
    public static final int MESSAGE_KEY_SEND = 6;

    // Key names received from the BluetoothService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";
	
	private SimpleAppConfiguration m_sac = new SimpleAppConfiguration();
    private Platform m_platform = new Platform();
    
    private static final int DIALOG_CONNECTION_REQUIRED = 0;
	private static final int DIALOG_LINKEDIN_OAUTH = 1;
	private static final int DIALOG_ASK_FOR_NAME = 2;
	private static final int DIALOG_CONNECT_TO_SCREEN = 3;
	
	private Set<String> m_in_range = Collections.synchronizedSet(new HashSet<String>());
	private Set<String> m_screen_in_range = Collections.synchronizedSet(new HashSet<String>());
	private static String owner_name;
	private ViewSwitcher switcher;
	
	private BluetoothService bluetooth_service = null;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.i("STATE", "OnCreate");
        
        this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
        
        // set screen bt address to null
        screen_bt = null;
        bluetooth_service = new BluetoothService(this, mHandler);
        
    	// Bluetooth
    	BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    	if (mBluetoothAdapter == null) {
    		// Device does not support Bluetooth. End the activity.
    	    temp.this.finish();
    	} else {
    		// enable Bluetooth if is disabled
    		if (!mBluetoothAdapter.isEnabled()) {
    		    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    		    startActivityForResult(enableBtIntent, 1);
    		}
    	}    	
    	
        if (isOnline()) {
    		Log.i(TAG, "CONNECTED"); 
    		
    		// LocalSocial
    		m_localsocial = configureLocalSocial();
    		m_localsocial.getNeighbourhood().observeNeighbourhood(getNeighbourhoodObserver());
    		m_remote = m_localsocial.getRemoteFactory();
			doLocalSocialOAuth();
			
			// LinkedIn			
			if (!isLinkedInAuthorised()) {
				Log.i(TAG, "Authorising with LinkedIn");
				showDialog(DIALOG_LINKEDIN_OAUTH);			
			} else {
				Log.i(TAG, "Authorised with LinkedIn");
				Toast.makeText(getApplicationContext(), "Authorized with LinkedIn", Toast.LENGTH_LONG).show();
			}			
			
    	} else {
    		Log.d(TAG, "NOT CONNECTED");    		
    		showDialog(DIALOG_CONNECTION_REQUIRED);
    	}
        
        if (m_localsocial != null) {
    		startScan();
    	}
        
       // deleteAllTags();
        if (!prefs.contains("owner")){
        	showDialog(DIALOG_ASK_FOR_NAME);        
        }
        
        getAllTags();
        
//        int i = 0;
//        String available_screens[] = new String[10];
//        Iterator<String> it = m_screen_in_range.iterator();
//        while (it.hasNext()) {
//        	available_screens[i++] = it.next();
//        }
//        
//        ListView list_view =(ListView)findViewById(R.id.list_view);
//        list_view.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , available_screens));
    }
    
    /**
     * This method is a callback for enableBTintent
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if(requestCode == 0){
    		Log.i(TAG,"LinkedIn Authorised");
    	} else if (requestCode == 1){
    		m_localsocial = configureLocalSocial();                 
            Log.i(TAG, "BT was enabled");        
    	} else if (requestCode == 2) {
    		Log.i(TAG, "LinkedIn Auth");
    	}
    }
    
    /**
     * Handler
     */
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                switch (msg.arg1) {
                case BluetoothService.STATE_CONNECTED:
                    break;
                case BluetoothService.STATE_CONNECTING:
                	Toast.makeText(getApplicationContext(), "Connecting to the screen...", Toast.LENGTH_SHORT).show();
                	break;
                case BluetoothService.STATE_LISTEN:
                case BluetoothService.STATE_NONE:
                    break;
                }
                break;
            case MESSAGE_WRITE:
               
                break;
            case MESSAGE_READ:

                break;
            case MESSAGE_DEVICE_NAME:
               
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                               Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };
    
    /**
     * Get the LocalSocial configuration
     * @return
     */
    public LocalSocial.Configuration getConfig() {
        return m_localsocial.getConfig();
    }
    
    /**
     * 
     * @param target
     */
    public void pressButton(View target){
    	switch(target.getId()){
    	case R.id.button_down:
    		Log.i("Click","down"); 
    		sendMessage("down");
    		break;
    	case R.id.button_left:
    		Log.i("Click","left"); 
    		sendMessage("left");
    		break;
    	case R.id.button_right:
    		Log.i("Click","right"); 
    		sendMessage("right");
    		break;
    	case R.id.button_up:
    		Log.i("Click","up"); 
    		sendMessage("up");
    		break;
    	case R.id.button_select:
    		Log.i("Click","select");
    		sendMessage("select");
    		break;
    	}
    }
    
    /**
     * Called when Connect button is pressed. Connects to a Screen.
     */
    public void connectToScreen(String address){
//    	if (screen_bt != null) {
//	    	if (bluetooth_service.getState() != BluetoothService.STATE_CONNECTED) {
//	        	String addr = fixAddress(screen_bt.substring(2));
//	            bluetooth_service.connect(BluetoothAdapter.getDefaultAdapter().getRemoteDevice(addr));
//	            
//	            sendAuthToken();
//	        }
//    	} else {
//    		Toast.makeText(getApplicationContext(), "No screen in range",
//                    Toast.LENGTH_SHORT).show();
//    	}
    	
    	if (bluetooth_service.getState() != BluetoothService.STATE_CONNECTED) {
        	String addr = fixAddress(address.substring(2));
            bluetooth_service.connect(BluetoothAdapter.getDefaultAdapter().getRemoteDevice(addr));
            
            sendMessage("right");            
            sendAuthToken();          
        }
    	
    	try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
    	
    	if (bluetooth_service.getState() == BluetoothService.STATE_CONNECTED ||
    			bluetooth_service.getState() == BluetoothService.STATE_CONNECTING) {
    		switcher = (ViewSwitcher) findViewById(R.id.switcher);
            switcher.showNext();
            
            sendAuthToken();
    	}
    }
    
    /**
     * This method sends messages to the connected device
     * @param message to be passed via Bluetooth
     */
    private void sendMessage(String message) {
    	if (screen_bt != null) {
	        if (bluetooth_service.getState() != BluetoothService.STATE_CONNECTED) {
	        	String addr = fixAddress(screen_bt.substring(2));
	            bluetooth_service.connect(BluetoothAdapter.getDefaultAdapter().getRemoteDevice(addr));
	        }
	
	        byte[] send = message.getBytes();
	        bluetooth_service.write(send);
    	} else {
    		Toast.makeText(getApplicationContext(), "No screen in range",
                    Toast.LENGTH_SHORT).show();
    	}
    }
    
    /**
     * Send LinkedIn access token to the screen
     */
    private void sendAuthToken() {
    	Log.d("SP", "sending token");
    	String token = this.prefs.getString(OAuth.OAUTH_TOKEN,"");
        String secret = this.prefs.getString(OAuth.OAUTH_TOKEN_SECRET,"");        
        String info = "OAUTH:"+token+":"+secret;
        Log.d("SP", info);
        byte[] sendInfo = info.getBytes();
        bluetooth_service.write(sendInfo);
    }
    
    /**
     * Get Bluetooth MAC address of the current device
     * @return
     */
    public String getAddress() {
        if (m_address == null) {
            m_address = getConfig().getAddress();
            if (m_address == null) {
                m_address = m_localsocial.getNeighbourhood().getAddress();
            }
        }
        return m_address;
    }
    
    /**
     * Called when activity is stopped
     */
    @Override
    public void onStop() {
    	final Editor edit = prefs.edit();
		edit.putBoolean("authorised", false);
		edit.commit();
    	Log.i("STATE", "OnStop");
    	super.onStop();
    }
    
    /**
     * Called when activity is resumed
     */
    @Override
    public void onResume() {
    	super.onResume();
    	Log.i("STATE", "OnResume");
    }
    
    /**
     * Called when activity is restarted
     */
    @Override
    public void onRestart() {
    	super.onRestart();
    	Log.i("STATE", "OnRestart");
    }
    
    /**
     * A final call before activity is destroyed
     */
    @Override
    public void onDestroy() {
    	super.onDestroy();
    	Log.i("STATE", "OnDestroy");
    }
    
    /**
     * Show menu
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
    
    /**
     * When a menu item is clicked
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {           
            case R.id.change_user:
            	clearLinkedInCredentials();
            	showDialog(DIALOG_LINKEDIN_OAUTH);
            	break;
            case R.id.make_discoverable:
            	Intent discoverableIntent = new
            	Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            	discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            	startActivity(discoverableIntent);
            	break;
            case R.id.disconnect:            	        
                switcher = (ViewSwitcher) findViewById(R.id.switcher);
                switcher.showNext();                  
            	break;
            case R.id.connections:
            	if (bluetooth_service.getState() == BluetoothService.STATE_CONNECTED) {                	
                    sendMessage("connections");          
                } else {
                	Toast.makeText(getApplicationContext(), 
                			"Device is not connected to Screen", Toast.LENGTH_LONG).show();
                }
            	break;
            case R.id.possible_connections:
            	if (bluetooth_service.getState() == BluetoothService.STATE_CONNECTED) {                	
                    sendMessage("possibleConnections");          
                } else {
                	Toast.makeText(getApplicationContext(), 
                			"Device is not connected to Screen", Toast.LENGTH_LONG).show();
                }
            	break;
            case R.id.employees:
            	if (bluetooth_service.getState() == BluetoothService.STATE_CONNECTED) {                	
                    sendMessage("employees");          
                } else {
                	Toast.makeText(getApplicationContext(), 
                			"Device is not connected to Screen", Toast.LENGTH_LONG).show();
                }
        }
        return true;
    }
    
    /**
     * Configure LocalSocial
     * @return
     */
    protected LocalSocial configureLocalSocial() {     	
    	m_sac = new SimpleAppConfiguration();    	
    	m_sac.setServiceName(Constants.LS_NAME);
    	m_sac.setConsumerKey(Constants.LS_KEY);
        m_sac.setConsumerSecret(Constants.LS_SECRET);
        m_sac.setAuthCallback(Constants.LS_CALLBACK);
        
        m_platform = new Platform();        
        m_platform.setContext(getApplication());
        
        m_sac.setPlatformContext(m_platform);        
        LocalSocialFactory.setDefaultConfig(m_sac);
        
        return LocalSocialFactory.getLocalSocial();       
    }
    
    /**
     * Authenticate with LocalSocial
     */
    public void doLocalSocialOAuth() {
		if (m_localsocial != null) {
			Log.i(TAG, "LOCAL SOCIAL INITIALISED");
			Log.i(TAG, "Starting OAuth");
	        m_consumer = m_localsocial.getOAuthConsumer();
	        m_access_token = null;
	        
	        try {
	        	m_access_token = m_localsocial.loadAccessToken();
	        	Log.i(TAG, "Using existing token");
	        } catch (UnauthorizedException e) {
	        	Log.i(TAG, "No token");
	        	Log.i(TAG, m_localsocial.toString());
	        	RequestToken token = null;
	        	
	        	try {
	        		 token = m_consumer.generateRequestToken();
	        		 Verifier verifier = m_consumer.authorise(token);
	        		 m_access_token = m_consumer.exchange(token, verifier);
	        		 m_localsocial.saveAccessToken(m_access_token);
	        		 Log.i(TAG, "New token generated");
	        	} catch (UnauthorizedException unauth) {
	        		Log.i(TAG, "Unauthorized Exception", unauth);
	        	} catch (IOException io) {
					Log.i(TAG, "IO Exception", io);
				}   		        	
	        }
		} else {
			Log.i(TAG, "LOCAL SOCIAL NULL");
		}
    }
   
    /**
     * Clear the LinkedIn credentials saved in shared preferences
     */
    public void clearLinkedInCredentials() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		final Editor edit = prefs.edit();
		edit.remove(OAuth.OAUTH_TOKEN);
		edit.remove(OAuth.OAUTH_TOKEN_SECRET);
		edit.commit();
	}
    
    /**
     * This method checks if a user is authorised with LinkedIn
     */
    public boolean isLinkedInAuthorised() {
    	boolean temp = this.prefs.getBoolean("authorised", false);
    	String token = this.prefs.getString(OAuth.OAUTH_TOKEN,"");
    	Map<String,?> a = this.prefs.getAll();
    	
    	for(String key:a.keySet()){
    		Log.i("SP",key+": "+a.get(key).toString());
    	}
    	Log.i("SP", "AUTH? "+ temp);
    	Log.i("SP", "AUTH token = "+ token);
    	
    	return temp;
    }
    
	/**
	 * This method checks if a device is connected to a network
	 */
	public boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm.getActiveNetworkInfo() != null) {
			return cm.getActiveNetworkInfo().isConnectedOrConnecting();
		}		
		return false;
	}
	
	/**
     * Callback method for dialogs
     * @return 
     */
    public Dialog onCreateDialog(int id) {
    	Dialog dialog;
    	
    	switch (id){
    	case DIALOG_CONNECTION_REQUIRED:
    		AlertDialog.Builder builder_connection = new AlertDialog.Builder(this);
    		builder_connection.setMessage("Sorry, this application requries network connection." +
    				"Connect to a network and restart the application.")
    		       .setCancelable(false)
    		       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
    		           public void onClick(DialogInterface dialog, int id) {
    		                temp.this.finish();
    		           }
    		       });
    		dialog = builder_connection.create();
    		break;
    	case DIALOG_LINKEDIN_OAUTH:
    		final View view = getWindow().getDecorView().findViewById(android.R.id.content);
    		
    		AlertDialog.Builder builder_oauth = new AlertDialog.Builder(this);
    		builder_oauth.setMessage("Please Authenticate with LinkedIn")
    		       .setCancelable(false)
    		       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
    		           public void onClick(DialogInterface dialog, int id) {
    		        	   startActivityForResult(new Intent().setClass(getApplicationContext(), PrepareRequestToken.class), 2);
    		           }
    		       })
    		       .setNegativeButton("Back", new DialogInterface.OnClickListener() {
    		           public void onClick(DialogInterface dialog, int id) {
    		        	   dialog.cancel();
    		           }
    		       });
    		dialog = builder_oauth.create();
    		break;
    	case DIALOG_ASK_FOR_NAME:
    		Log.i("SP","Name dialog");
    		AlertDialog.Builder builder_name = new AlertDialog.Builder(this);
    		final EditText input = new EditText(this);
    		builder_name.setView(input)
    			.setCancelable(false)
    			.setMessage("Please enter your name:")
    			.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    			public void onClick(DialogInterface dialog, int whichButton) {
    			  Editable value = input.getText();
    			  owner_name = value.toString();
    			  final Editor edit = prefs.edit();
    			  edit.putString("owner", owner_name);
    			  edit.commit();
    			  setTag(Constants.LS_NAMESPACE, Constants.LS_OWNER_NAME, owner_name, getAddress());
    			  }
    			});
    		dialog = builder_name.create();
    		break;
    	case DIALOG_CONNECT_TO_SCREEN:
    		AlertDialog.Builder builder_connect = new AlertDialog.Builder(this);
    		builder_connect.setMessage("Screen is in range. Do you want to connect?")
		       .setCancelable(false)
		       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	  // connectToScreen();
		           }
		       })
		       .setNegativeButton("Back", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   dialog.cancel();
		           }
		       });
		dialog = builder_connect.create();
		break;
    		
    	default:
    		dialog = null;
    	}  	
    			
		return dialog;   	
    }
    
    /**
     * Create new tag task
     * @param namespace
     * @param name
     * @param value
     * @param target
     * @return 
     */
    public SetTagTask setTag(String namespace, String name, String value, String target) {
        SetTagTask task = new SetTagTask();
        task.execute(namespace, name, value, target);
        return task;
    }
    
    /**
     * Async task for creating or updating tags
     */
    class SetTagTask extends AsyncTask<String, Void, Exception> {
        String namespace;
        String name;
        String value;
        String target;

        @Override
        protected Exception doInBackground(String... params) {
            namespace = params[0];
            name = params[1];
            value = params[2];
            target = params[3];

            Exception e = null;
            try {
                m_remote.getTagRemote().updateOrCreate(namespace, name, value, target);
            } catch (Exception ex) {
                e = ex;
            }
            return e;
        }

        protected void onPostExecute(Exception e) {
            if (e == null) {                
//                String msg = "Set " + name + " to " + value;
//                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    };
    
    /*
     * Get all tags associated with the current device and namespace
     */
    public GetAllTagsTask getAllTags() {
        GetAllTagsTask task = new GetAllTagsTask();
        task.execute();
        return task;
    }
    
    /**
     * Async Task for retrieving all tags associated with the current device and namespace
     */
    class GetAllTagsTask extends AsyncTask<String, Void, Exception> {
    	Tag[] tags;

        @Override
        protected Exception doInBackground(String... params) {
        	tags = null;        	
            Exception e = null;
            try {
            	tags = m_remote.getTagRemote().get(Tag.TAG_ANY, getAddress());
            } catch (Exception ex) {
                e = ex;
            }
            return e;
        }

        protected void onPostExecute(Exception e) {
        	String screen = null;
            if (e == null) {                
            	if(tags != null && tags.length != 0){
                	String allTags = "";
                    for(Tag tag: tags){
                    	if(tag.getName().contains("TabMacAddress")){
                    		screen = tag.getOwner();
                    		Log.i("Tags", "Tab's address read");
                    		Log.i("Tags", "In range: " + m_in_range.toString());
                    		if(m_in_range.contains(screen)){
                    			m_screen_in_range.add(screen);
                    			Log.i("Tags", "Screen in range: " + screen);
                    		}
                    	}
                        StringBuffer sb = new StringBuffer("tag[").append(tag.getName()).append("]=");
                        sb.append(tag.getValue());                        
                        allTags += sb.toString();
                    }
                    
                    Log.d("Tags", "All tags = " + allTags);
                    Log.d("Tags", "owner set?" +new Boolean(screen == null).toString());
                    if (screen != null && screen_bt != screen){
                    	screen_bt = screen;
                    	m_screen_in_range.add(screen);
                    }
                    
                    Log.d("Tags", "Screens in range = " + m_screen_in_range.size());
                    
                    displayAvailableScreens();
                    
                    Log.d("Tags" , "Screen address = " + screen_bt);
                }
            }
        }
    };
    
    public void displayAvailableScreens(){
    	int i = 0;
        String available_screens[] = new String[m_screen_in_range.size()];
        Iterator<String> it = m_screen_in_range.iterator();
        Log.i("Stuff", m_screen_in_range.toString());
        while (it.hasNext()) {
        	Log.i("Stuff", "i = " + i);
        	available_screens[i] = "Screen" + i;        	
        	it.next(); i++;
        }
        
        ListView list_view =(ListView)findViewById(R.id.list_view);
        list_view.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , available_screens));
        
        list_view.setOnItemClickListener(new OnItemClickListener() {
            @Override
			public void onItemClick(AdapterView<?> adapter, View view, int pos,
					long arg3) {
            	connectToScreen(screen_bt);
			}
          });
    }
    
    /*
     * Delete all tags associated with the current device and namespace
     */
    public DeleteAllTagsTask deleteAllTags() {
        DeleteAllTagsTask task = new DeleteAllTagsTask();
        task.execute();
        return task;
    }    
    
    /**
     * Async Task for deleting all tags associated with the current device and namespace
     */
    class DeleteAllTagsTask extends AsyncTask<String, Void, Exception> {
    	Tag[] tags;

        @Override
        protected Exception doInBackground(String... params) {
        	tags = null;        	
            Exception e = null;
            try {
            	tags = m_remote.getTagRemote().get(Tag.TAG_ANY, getAddress());
            } catch (Exception ex) {
                e = ex;
            }
            return e;
        }

        protected void onPostExecute(Exception e) {
            if (e == null) {                
            	if(tags != null && tags.length != 0){
                    for(Tag tag: tags){
                    	Log.i("DELETE", "Deleting tag name: " + tag.m_name + ", value: " + tag.m_value);
                        try {
        					m_remote.getTagRemote().delete(tag);
        				} catch (ParseException ex) {
        					Log.i("DELETE", "Delete tag error " + ex);
        				} catch (IOException ex) {
        					Log.i("DELETE", "Delete tag error " + ex);
        				}
                    }
                }
            }
        }
    };
        
    /**
     * Change the Bluetooth MAC address representation
     * @param String Bluetooth MAC address in the form btxxxxxxxxxxxx
     * @return String Bluetooth MAC address in the form XX:XX:XX:XX:XX:XX
     */
    private String fixAddress(String address){
    	String value = "";
    	for (int i=0; i<address.length(); i=i+2){
    		value += address.substring(i, i+2);
    		if (i%2 == 0 && i<address.length()-2){
    			value += ":";
    		}    		
    	}
    	return value.toUpperCase();
    }
    
    protected NeighbourhoodObserver getNeighbourhoodObserver() {
        return m_nobby;
    }
    
    NeighbourhoodObserver m_nobby = new NeighbourhoodObserver() {

        @Override
        public void discovered(Device device) {
        	Log.i("NOBBY", "Device discovered " + device.getAddress());
            String address = device.getAddress();
            if (!m_in_range.contains(address)) {
                m_in_range.add(address);
            }
        }

        @Override
        public void inRange(Device device) {
        	Log.i("NOBBY", "Device in range " + device.getAddress());
        	String address = device.getAddress();
            if (!m_in_range.contains(address)) {
                m_in_range.add(address);
            }
        }
        
        @Override
        public void outOfRange(Device device) {
        	Log.i("NOBBY", "Device out of range");
        	String address = device.getAddress();
            if (m_in_range.contains(address)) {
                m_in_range.remove(address);
            }
            if (m_screen_in_range.contains(address)) {
            	m_screen_in_range.remove(address);
            }
        }

        @Override
        public void scanStarted(boolean first) {
        	Log.i("NOBBY", "Scan started");
        }

        @Override
        public void scanStopped(int result) {
        	Log.i("NOBBY", "Scan stopped");
        }

		@Override
		public void scanModeChanged(int arg0) {
			Log.i("NOBBY", "Scan mode changed");
		}
        
    };
    
    
    /**
     * Stop the current periodic scan
     */
    protected void stopScan() {    	
        if (m_scan != null) {
            Log.d(TAG, "stop scan");
            m_scan.stop();
            m_scan = null;
            Log.i(TAG, "Scan is stopped");
        } else {
            Log.d(TAG, "not scanning");
        }
    }

    /**
     * Start a new scan
     */
    protected void startScan() {
    	Log.i(TAG, "Starting scan");
        m_scan = m_localsocial.getNeighbourhood().startScan();
        if (m_scan == null) {
        	Log.w("TAG", "scan is null");
        }
    }

    /**
     * Stop the current scan if there is one and then start a new one
     */
    protected void restartScan() {
    	Log.i(TAG, "Restarting scan");
        stopScan();
        startScan();
    }  
    
    protected void doBluetoothStuff(){
    	String bt_addrress = fixAddress(screen_bt.substring(2));
    	Log.i("Bluetooth Stuff",bt_addrress+", "+Boolean.toString(BluetoothAdapter.checkBluetoothAddress(bt_addrress)));
    	Log.i("Bluetooth Stuff",BluetoothAdapter.getDefaultAdapter().getRemoteDevice(bt_addrress).toString());
    }
}